'use strict'
import isEmpty from 'lodash/isEmpty'
import isString from 'lodash/isString'
import WebCookie from '../html/cookie/WebCookie'
import * as UrlUtils from '../core/utils/UrlUtils'

/**
 * 格式化语言，例如将 zh-cn 转为 zh-CN
 */
function formatLocale(lang: string): string {
  const [lang1, lang2] = lang.split('-')
  return lang2 ? [lang1, lang2.toUpperCase()].join('-') : lang
}

/**
 * 兼容语言机制
 */
function compatLocale(lang: string): string {
  return lang.split('-')[0]
}

/**
 * 检测语言机制，默认从 URL、cookie、浏览器中依次获取，直到获取到值为止
 */
function determineLocale(requestLocaleName, defaultLocale) {
  return formatLocale(getLocaleFromURL(requestLocaleName) || getLocaleFromCookie(requestLocaleName) || getLocaleFromBrowser(defaultLocale))
}

function getLocaleFromURL(requestLocaleName: string[]) {
  if (!window.location) {
    return null
  }
  const urlQuery = UrlUtils.parse().getQuery()
  if (urlQuery !== null) {
    for (let i = 0, l = requestLocaleName.length; i < l; i++) {
      const name = requestLocaleName[i]
      if (urlQuery.hasOwnProperty(name)) {
        return urlQuery[name]
      }
    }
  }
}

function getLocaleFromCookie(requestLocaleName) {
  if (!document.cookie) {
    return null
  }
  for (let i = 0, l = requestLocaleName.length; i < l; i++) {
    const lang = WebCookie.get(requestLocaleName[i])
    if (!isEmpty(lang) && isString(lang)) {
      return lang
    }
  }
}

function getLocaleFromBrowser(defaultLocale: string) {
  let browserLocale = ''
  if (window.navigator) {
    browserLocale = navigator.language || navigator['userLanguage']
  }
  return browserLocale || defaultLocale
}

export { formatLocale, compatLocale, determineLocale }
